<?php

class hdms_userController extends FoundryControllerInterface
{


	/**
	 * init()
	 *
	 * init() is called in place of the __construct() method used by the
	 * FoundryControllerInterface super class
	 * This function will be called immediately after the __construct method
	 *
	 */ 
	public function init()
	{
	
	
	}
	
	public function main()
	{
	
		return true;
	}
	
	/**
	 * pretty self explanatory, get the form fields, make sure they don't
	 * contain any nasty stuff (or just strip it out, rather) run the
	 * username and password against the DB, if it's correct send them on their
	 * way, otherwise give them the form again
	 *
	 */
	public function authenticate()
	{
		$user = FoundryRegistry::get( 'USER_session' );
		
		$username = FoundryRequest::post( 'username', 'alnum' );
		$password = FoundryRequest::post( 'password', 'alnum' );

		$error = false;

		if( $user->checkKey() && $username && $password ) {

			$userModel = $this->user();

			$data = $userModel->find( '*username = :un and *password = :pw',
				array( ':un' => $username, ':pw' => md5( $password ) ) );
				

			if( $data[0]->uid && $data[0]->username == $username &&
				$data[0]->locked + AUTH_TIMEOUT <= time() ) {
				$user->set( 'isAuthenticated', 1 );
				$user->set( 'lastActive', time() );

				$data[0]->sess_id = $user->id();
				$data[0]->locked = 0;
				$data[0]->tries = 0;
				
				$data[0]->save();
				
				$mods = FoundryController::config( 'modules' );

				$key = $mods['newsAdmin']['__obKey'];

				header( "Location: ".Foundry::config( 'webpath' ).'/index.php'.
					'/'.$key );
				exit;
			}
	
			$error = 'Login incorrect!';

			$data = $userModel->find( '*username = :un',
				array( ':un' => $username ) );

			if( $data[0]->uid ) {
				$data[0]->tries = $data[0]->tries + 1;
	
				if( $data[0]->tries >= AUTH_EXHAUST ) {
					$data[0]->locked = time();
					$error = 'Maximum incorrect attempts. Login is locked.';
				}

				$data[0]->save();
			}
			
		}
		
		$key = $user->generateKey();

		return array( 'key'	=> $key, 'error' => $error );
	}
	
	public function deauthenticate()
	{
		$user = FoundryRegistry::get( 'USER_session' );
		
		$id = $user->id();
		
		$userModel = $this->user();
		
		$data = $userModel->find( '*sess_id = :sid',
			array( ':sid' => $id ) );
			
		if( $data[0]->uid ) {
			$data[0]->sess_id = -1;
			$data[0]->save();
			
			$user->destroy();
		}
		
		header( "Location: ".Foundry::config( 'webpath' ).'/index.php' );
		exit;
	}

}

?>